﻿Imports System.Collections.Specialized
Imports Microsoft.TeamFoundation.Client
Imports Microsoft.TeamFoundation.WorkItemTracking.Client
Imports System.Windows.Media.Animation
Imports System.Windows.Threading
Imports System.IO
Imports System.Net

Class MainWindow

    Private ItemWrappers As ItemCollection = Application.ItemWrappers

    Public Shared ReadOnly ChangeSkinCommand As RoutedCommand = New RoutedCommand("ChangeSkin", GetType(MainWindow))
    Public Shared ReadOnly ChangeLifeCycleCommand As RoutedCommand = New RoutedCommand("ChangeLifeCycle", GetType(MainWindow))
    Public Shared ReadOnly ChangeTeamServerCommand As RoutedCommand = New RoutedCommand("ChangeTeamServer", GetType(MainWindow))
    Public Shared ReadOnly ChangeTeamProjectCommand As RoutedCommand = New RoutedCommand("ChangeTeamProject", GetType(MainWindow))
    Public Shared ReadOnly SelectStoredQueryCommand As RoutedCommand = New RoutedCommand("SelectStoredQuery", GetType(MainWindow))
    Public Shared ReadOnly DisplayByCommand As RoutedCommand = New RoutedCommand("DisplayBy", GetType(MainWindow))
    Public Shared ReadOnly CodeplexCommand As RoutedCommand = New RoutedCommand("Codeplex", GetType(MainWindow))

    Public Sub New()
        ' This call is required by the Windows Form Designer.
        InitializeComponent()
        ' Add any initialization after the InitializeComponent() call.
        Me.WorkingUserControl.Window = Me
        Me.CredentialProviderBox.Window = Me
        Me.WelcomeUserControl.Window = Me

        Me.WelcomeUserControl.Refresh()

        BuildSkinsMenu()
        ShowWelcomeScreen()
        BuildTeamServerMenu()
        BuildProjectsMenu()
        BuildStoredQueryMenu()
        BuildDisplayByMenu()
        BuildLifeCyclesMenu()

        '' Icon bit
        'Dim iconStream As New MemoryStream()
        'My.Resources.RDIcon.Save(iconStream)
        'iconStream.Seek(0, SeekOrigin.Begin)
        'Me.Icon = BitmapFrame.Create(iconStream)
    End Sub

#Region " Menus "

    ''' <summary>
    ''' Builds the Skins Menu
    ''' </summary>
    Private Sub BuildSkinsMenu()
        ' Clear existing menu items
        SkinsMenu.Items.Clear()
        Dim skins As NameValueCollection = Application.Skins
        For Each skinName As String In skins.AllKeys
            Dim skin As MenuItem = New MenuItem()
            skin.Header = skinName
            skin.CommandParameter = skins(skinName)
            skin.Command = ChangeSkinCommand
            skin.IsCheckable = True
            skin.IsChecked = (My.Settings.Skin.Contains(skinName))
            SkinsMenu.Items.Add(skin)
        Next
    End Sub

    ''' <summary>
    ''' Builds the Skins Menu
    ''' </summary>
    Private Sub BuildLifeCyclesMenu()
        ' Clear existing menu items
        LifeCyclesMenu.Items.Clear()
        Dim LifeCycles As NameValueCollection = Application.LifeCycles
        For Each LifeCycleName As String In LifeCycles.AllKeys
            Dim LifeCycle As MenuItem = New MenuItem()
            LifeCycle.Header = LifeCycleName
            LifeCycle.CommandParameter = LifeCycles(LifeCycleName)
            LifeCycle.Command = ChangeLifeCycleCommand
            LifeCycle.IsCheckable = True
            LifeCycle.IsChecked = (My.Settings.LifeCycle.Contains(LifeCycleName))
            LifeCyclesMenu.Items.Add(LifeCycle)
        Next
    End Sub

    ''' <summary>
    ''' Builds the Team Server list menu
    ''' </summary>
    Private Sub BuildTeamServerMenu()
        ' Clear existing menu items
        ConnectMenu.Items.Clear()
        '' Add the recent files to the menu as menu items
        For Each svrnme As String In RegisteredServers.GetServerNames
            Dim svr As New TeamFoundationServer(svrnme, CredentialProviderBox)
            Dim item As MenuItem = New MenuItem()
            item.Header = svr.Name
            item.CommandParameter = svr
            item.Command = ChangeTeamServerCommand
            item.IsCheckable = True
            If Not Application.TFServer Is Nothing Then
                item.IsChecked = (svr.Uri Is Application.TFServer.Uri)
            End If
            ConnectMenu.Items.Add(item)
        Next
    End Sub

    ''' <summary>
    ''' Builds the List of work item types for a project
    ''' </summary>
    Private Sub BuildStoredQueryMenu()
        ' Clear existing menu items
        WorkItemQueryMenu.Items.Clear()
        If Not Application.SelectedProject Is Nothing Then
            For Each sq As StoredQuery In Application.SelectedProject.StoredQueries
                Dim item As MenuItem = New MenuItem()
                item.Header = sq.Name
                item.CommandParameter = sq
                item.IsCheckable = True
                item.IsChecked = (Application.SelectedStoredQuery Is sq)
                item.Command = SelectStoredQueryCommand
                WorkItemQueryMenu.Items.Add(item)
            Next
        Else
            Dim item As MenuItem = New MenuItem()
            item.Header = "You must first select a team project..."
            WorkItemQueryMenu.Items.Add(item)
        End If
    End Sub

    ''' <summary>
    ''' Builds the List of work item types for a project
    ''' </summary>
    Private Sub BuildProjectsMenu()
        ' Clear existing menu items
        ProjectsMenu.Items.Clear()
        If Not Application.TFServer Is Nothing AndAlso Application.TFServer.HasAuthenticated Then
            For Each p As Project In Application.WorkItemStore.Projects
                If p.HasWorkItemWriteRights Then
                    Dim item As MenuItem = New MenuItem()
                    item.Header = p.Name
                    item.CommandParameter = p
                    item.Command = ChangeTeamProjectCommand
                    item.IsCheckable = True
                    item.IsChecked = (p Is Application.SelectedProject)
                    ProjectsMenu.Items.Add(item)
                End If
            Next
        Else
            Dim item As MenuItem = New MenuItem()
            item.Header = "You must first connect to a team server..."
            ProjectsMenu.Items.Add(item)
        End If
    End Sub

    ''' <summary>
    ''' Builds the List of work item types for a project
    ''' </summary>
    Private Sub BuildDisplayByMenu()
        ' Clear existing menu items
        DisplayByMenu.Items.Clear()

        For Each e As Node.TreeType In [Enum].GetValues(GetType(Node.TreeType))
            Dim item As MenuItem = New MenuItem()
            item.Header = e.ToString
            item.CommandParameter = e
            item.Command = DisplayByCommand
            item.IsCheckable = True
            item.IsChecked = (e = Application.DisplayBy)
            DisplayByMenu.Items.Add(item)
        Next

    End Sub



#End Region

#Region " Command Handlers "

    ''' <summary>
    ''' Command handler for logo click event
    ''' </summary>
    Private Sub RDdotNet_MouseLeftButtonUp(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
        ' Open the RDdotNet website in the user's default browser
        System.Diagnostics.Process.Start("http://www.codeplex.com/TFSStickyBuddy")
    End Sub

#Region " ChangeTeamServer "

    Public Delegate Sub ChangeTeamServer_DoWorkHandler(ByVal server As TeamFoundationServer)
    Public Delegate Sub ChangeTeamServer_UIHandler(ByVal server As TeamFoundationServer, ByVal result As Boolean)

    Public Sub ChangeTeamServer_End(ByVal server As TeamFoundationServer, ByVal Result As Boolean)
        ' TODO: Suff to display everything
        If Result Then
            ShowDetailsPane()
            BuildTeamServerMenu()
            BuildProjectsMenu()
            BuildStoredQueryMenu()
            RefreshData()
        Else
            ShowWelcomeScreen()
        End If
    End Sub

    Private Sub ChangeTeamServer_DoWork(ByVal server As TeamFoundationServer)
        'WorkingUserControl.Update(Working.Actions.Start, "connecting to team server...", "connecting to team server...")
        Dim Result As Boolean = False
        Try
            'WorkingUserControl.Update(Working.Actions.Progress, "authenticating team server...", "authenticating team server...")
            server.Authenticate()
            ' WorkingUserControl.Update(Working.Actions.Progress, "updating selected team server..", "authenticatication complete..")
            Application.TFServer = server
            Result = True
            ' WorkingUserControl.Update(Working.Actions.Progress, "", "Completed update of selected server...")
        Catch ex As WebException
            MessageBox.Show(ex.Message, "Team Server communication error ", MessageBoxButton.OK, MessageBoxImage.Warning)
        Catch ex As Exception
            ' WorkingUserControl.Update(Working.Actions.Progress, ex.ToString, ex.Message)
            MsgBox(ex.ToString)
        End Try
        ' WorkingUserControl.Update(Working.Actions.Stop, "", "Done...")
        Dim UpdateTeamServerUIHandler As ChangeTeamServer_UIHandler = New ChangeTeamServer_UIHandler(AddressOf ChangeTeamServer_End)
        Me.Dispatcher.BeginInvoke(DispatcherPriority.Normal, UpdateTeamServerUIHandler, server, Result)
    End Sub

    ''' <summary>
    ''' Command handler for changing the selected Team Server
    ''' </summary>
    Private Sub ChangeTeamServer_Start(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs)
        HideWelcomeScreen()
        Dim tfs As TeamFoundationServer = CType(e.Parameter, TeamFoundationServer)
        ' Call Load ruteen on another thread
        Dim ltfsh As ChangeTeamServer_DoWorkHandler = New ChangeTeamServer_DoWorkHandler(AddressOf ChangeTeamServer_DoWork)
        ltfsh.BeginInvoke(tfs, Nothing, Nothing)
    End Sub

#End Region

    ''' <summary>
    ''' Command handler for changing the selected team project
    ''' </summary>
    Private Sub Codeplex(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs)
        Dim Param As String = e.Parameter
        Dim nav As String = "http://hinshelwood.com/TFSStickyBuddy.aspx"
        Select Case Param
            Case "Home"
                nav = "http://hinshelwood.com/TFSStickyBuddy.aspx"
            Case "Release"
                nav = "http://www.codeplex.com/TFSStickyBuddy/Release/ProjectReleases.aspx"
            Case "Discussions"
                nav = "http://www.codeplex.com/TFSStickyBuddy/Thread/List.aspx"
            Case "IssueTracker"
                nav = "http://www.codeplex.com/TFSStickyBuddy/WorkItem/AdvancedList.aspx"
            Case "SourceCode"
                nav = "http://www.codeplex.com/TFSStickyBuddy/SourceControl/ListDownloadableCommits.aspx"
            Case "License"
                nav = "http://www.codeplex.com/TFSStickyBuddy/license"
            Case Else
                nav = "http://hinshelwood.com/TFSStickyBuddy.aspx"
        End Select
        System.Diagnostics.Process.Start(nav)
    End Sub

    ''' <summary>
    ''' Command handler for changing the selected team project
    ''' </summary>
    Private Sub ChangeTeamProject(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs)
        Dim Project As Project = CType(e.Parameter, Microsoft.TeamFoundation.WorkItemTracking.Client.Project)
        Application.SelectedProject = Project
        Application.SelectedStoredQuery = Project.StoredQueries.Item(0)
        BuildProjectsMenu()
        BuildStoredQueryMenu()
        'TODO: Initiate refresh
        RefreshData()

    End Sub

    ''' <summary>
    ''' Command handler for changing the selected team project
    ''' </summary>
    Private Sub SelectStoredQuery(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs)
        Dim sq As StoredQuery = CType(e.Parameter, StoredQuery)
        If Application.SelectedStoredQuery Is sq Then
            Application.SelectedStoredQuery = Nothing
        Else
            Application.SelectedStoredQuery = sq
        End If
        BuildStoredQueryMenu()
        RefreshData()
    End Sub

    ''' <summary>
    ''' Command handler for changing the selected team project
    ''' </summary>
    Private Sub DisplayBy(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs)
        Dim tt As Node.TreeType = CType(e.Parameter, Node.TreeType)
        Application.DisplayBy = tt
        BuildDisplayByMenu()
        RefreshData()
    End Sub

    ''' <summary>
    ''' Command handler for ChangeSkinCommand
    ''' </summary>
    Private Sub ChangeSkin(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs)
        Application.PopulateResources(e.Parameter, My.Settings.LifeCycle)

        ' save the skin setting
        My.Settings.Skin = CStr(e.Parameter)
        My.Settings.Save()

        BuildSkinsMenu()

        ' TODO: Refresh bits that need refreshing
        ItemWrappers.OnContentChanged()
        'ItemInfoControl.OnSkinChanged()
    End Sub

    ''' <summary>
    ''' Command handler for ChangeLifeCycleCommand
    ''' </summary>
    Private Sub ChangeLifeCycle(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs)

        Application.PopulateResources(My.Settings.Skin, e.Parameter)
        ' save the skin setting
        My.Settings.LifeCycle = CStr(e.Parameter)
        My.Settings.Save()

        BuildLifeCyclesMenu()

        ' TODO: Refresh bits that need refreshing
        ItemWrappers.OnContentChanged()
        'ItemInfoControl.OnSkinChanged()
    End Sub

#End Region

    ''' <summary>
    ''' Show the Welcome Screen user control and hides the other controls.
    ''' </summary>
    Friend Sub ShowWelcomeScreen()
        HideDetailsPane()
        'DiagramControl.Visibility = Visibility.Hidden
        WelcomeUserControl.Visibility = Visibility.Visible
    End Sub


    '' <summary>
    '' Hides the Welcome Screen.
    '' </summary>
    Friend Sub HideWelcomeScreen()
        WelcomeUserControl.Visibility = Visibility.Hidden
    End Sub

    ''' <summary>
    ''' Displays the details pane
    ''' </summary>
    Private Sub ShowDetailsPane()
        ' TODO: Any Edit or details panels
        ' Add the cloned column to layer 0:
        'If Not DiagramPane.ColumnDefinitions.Contains(column1CloneForLayer0) Then
        '    DiagramPane.ColumnDefinitions.Add(column1CloneForLayer0)
        'End If

        'if (family.Current != null)
        '    DetailsControl.DataContext = family.Current;
        'DetailsPane.Visibility = Visibility.Visible
        'DetailsControl.SetDefaultFocus()

        HideWelcomeScreen()

        ConnectMenu.IsEnabled = True
        SkinsMenu.IsEnabled = True
        ProjectsMenu.IsEnabled = True
        DisplayByMenu.IsEnabled = True
        WorkItemQueryMenu.IsEnabled = True
        SearchPanel.IsEnabled = False
        LifeCyclesMenu.IsEnabled = True
    End Sub

    ''' <summary>
    ''' Hides the details pane
    ''' </summary>
    Private Sub HideDetailsPane()
        DetailsPane.Visibility = Visibility.Collapsed

        '' Remove the cloned columns from layers 0
        If DiagramPane.ColumnDefinitions.Contains(column1CloneForLayer0) Then
            DiagramPane.ColumnDefinitions.Remove(column1CloneForLayer0)
        End If

        ConnectMenu.IsEnabled = False
        SkinsMenu.IsEnabled = False
        ProjectsMenu.IsEnabled = False
        DisplayByMenu.IsEnabled = False
        WorkItemQueryMenu.IsEnabled = False
        SearchPanel.IsEnabled = False
        LifeCyclesMenu.IsEnabled = False
    End Sub


    Private Sub ShowWorking_StoryboardCompleted(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub HideWorking_StoryboardCompleted(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub RefreshData()
        Application.ItemWrappers.Clear()
        If Not Application.SelectedProject Is Nothing Then
            Dim Import As New TFSImport
            Import.Import(Application.ItemWrappers, Application.DisplayBy)
        Else
            MsgBox("No Project has been selected!")
        End If

    End Sub

#Region " SearchText "

    Private Sub SearchText_MouseEnter(ByVal sender As Object, ByVal e As System.Windows.Input.MouseEventArgs) Handles SearchText.MouseEnter
        If SearchText.Text = "[enter search]" Then
            SearchText.Text = ""
            SearchPanel.Opacity = 1
        End If
    End Sub

    Private Sub SearchText_MouseLeave(ByVal sender As Object, ByVal e As System.Windows.Input.MouseEventArgs) Handles SearchText.MouseLeave
        If SearchText.Text = "[enter search]" Or SearchText.Text = "" Then
            SearchText.Text = "[enter search]"
            SearchPanel.Opacity = 0.5
        End If
    End Sub

#End Region


    
    Private Sub CodeplexMenu_Home_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)

    End Sub

    Private Sub CodeplexMenu_Release_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)

    End Sub
End Class
